using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using VoteMeDefine;
using System.IO;
using System.Collections;
using System.Data.SqlServerCe;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Reflection;
using WinCE;




namespace VoteMe
{
    public partial class FrmMain : Form
    {
       

        public FrmMain()
        {
            InitializeComponent();
            
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            initForm();
        }



        private void initForm()
        {
            invisiableCtrlr();
            //read user info

            //read picture location
            TxtPath.Text = VariableDefine.picturePath;

            //read groups
            TxtGroups.Text = VariableDefine.groups;

            //read rates
            TxtRate.Text = VariableDefine.rates;

            //show picture box;
            //show main controller;
            PBShow.Visible = true;
            LBFileName.Visible = true;
            LbGroupsTitle.Visible = true;
            LbRateTitle.Visible = true;
            CmbGroups.Visible = true;
            CmbRate.Visible = true;
            BtnVote.Visible = true;
            BtnNext.Visible = true;
            BtnPrevious.Visible = true;
            LBMaxFile.Visible = true;
            TxtNowFile.Visible = true;
            BtnTo.Visible = true;

            //init groups and rate controller;
            //groups
            CmbGroups.Items.Clear();
            string[] strGroups = VariableDefine.groups.Split('|');
            if(VariableDefine.groups.Length!=0)
            {
                for (int i = 0; i < strGroups.Length; i++)
                {
                    CmbGroups.Items.Add(strGroups[i]);
                }
            }
            //rate
            CmbRate.Items.Clear();
            string[] strRates = VariableDefine.rates.Split('|');
            if (VariableDefine.rates.Length != 0)
            {
                for (int i = 0; i < strRates.Length; i++)
                {
                    CmbRate.Items.Add(strRates[i]);
                }
            }
            


            //read picture info from picture location;

            try
            {
                VariableDefine.alPicFileName.Clear();
                foreach (string flname in Directory.GetFiles(VariableDefine.picturePath))
                {
                    VariableDefine.alPicFileName.Add(flname);
                }

            PBShow.Image = imgMe(VariableDefine.alPicFileName[0].ToString());
            VariableDefine.strShowingPicFullName = VariableDefine.alPicFileName[0].ToString();
            getVote(VariableDefine.alPicFileName[0].ToString());
            LBMaxFile.Text = @"/" + VariableDefine.alPicFileName.Count;
            TxtNowFile.Text = @"1";
            TxtNowFile.SelectAll();
            TxtNowFile.Focus();
        }
        catch
        {

        }
        }
   
        private Image imgMe(string filePath)
        {
            try
            {
                //MessageBox.Show("PAUSE");
                ////Bitmap bt = new Bitmap(filePath);

                //System.Reflection.Assembly myAssembly;
                //myAssembly = System.Reflection.Assembly.Load("VoteMe");

                //System.Resources.ResourceSet rs=new System.Resources.ResourceSet(
                //Graphics gi = Graphics.FromHdc(m_hBitmap);
                Bitmap bt= Image.FromHbitmap(LoadViaDLL(filePath));
                //Bitmap bt = new Bitmap(filePath);
                int intNewWidth, intNewHeight;
                //for QVGA
                if (this.Width == 240)
                {
                    if ((bt.Width < 240) && (bt.Height < 180))
                    {
                        intNewWidth = bt.Width;
                        intNewHeight = bt.Height;
                    }
                    else
                    {
                        if (bt.Width > bt.Height)
                        {
                            //landscape
                            intNewWidth = 240;
                            intNewHeight = 240 * bt.Height / bt.Width;
                        }
                        else
                        {
                            //portrait
                            intNewHeight = 180;
                            intNewWidth = 180 * bt.Width / bt.Height;
                        }

                    }
                }
                else
                {
                    //for VGA
                    if ((bt.Width < 480) && (bt.Height < 360))
                    {
                        intNewWidth = bt.Width;
                        intNewHeight = bt.Height;
                    }
                    else
                    {
                        if (bt.Width > bt.Height)
                        {
                            //landscape
                            intNewWidth = 480;
                            intNewHeight = 480 * bt.Height / bt.Width;
                        }
                        else
                        {
                            //portrait
                            intNewHeight = 360;
                            intNewWidth = 360 * bt.Width / bt.Height;
                        }

                    }
                }
                Bitmap img = new Bitmap(intNewWidth, intNewHeight);
                Graphics g = Graphics.FromImage(img);
                g.DrawImage(bt, new Rectangle(0, 0, intNewWidth, intNewHeight), new Rectangle(0, 0, bt.Width, bt.Height), GraphicsUnit.Pixel);
                g.Dispose();
                bt.Dispose();
                return img;
            }
            catch 
            {
                Bitmap errimg = new Bitmap(480, 360);
                Graphics errg = Graphics.FromImage(errimg);
                errg.DrawString("Nonsupport file type!", new Font("Arial", 16, FontStyle.Regular), new SolidBrush(Color.Red), 5.0F, 5.0F);
                errg.Dispose();
                return errimg;
            }
            
            //throw new Exception("The method or operation is not implemented.");
        }

        //private bool isImg(string filePath)
        //{
        //    try
        //    {
        //        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        //        int byteLength = (int)fs.Length;
        //        byte[] stImg = new byte[byteLength];
        //        fs.Read(stImg, 0, byteLength);
        //        fs.Close();
        //        Bitmap bt = new Bitmap(new MemoryStream(stImg));
        //        bt.Dispose();
        //        return true;
        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //}


        private void MiExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void BtnPath1_Click(object sender, EventArgs e)
        {
            FolderChoice frmFolder = new FolderChoice();
            frmFolder.Show();
            this.Close();
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            
            invisiableCtrlr();
            LblTitle.Visible = true;
            LblPath.Visible = true;
            TxtPath.Visible = true;
            BtnPath.Visible = true;
            BtnPath.Focus();
        }

        private void MiMain_Click(object sender, EventArgs e)
        {
            initForm();
        }

        private void invisiableCtrlr()
        {
            foreach (Control c in this.Controls)
            {
                c.Visible = false;
            }
        }

        private void MiGroups_Click(object sender, EventArgs e)
        {
            invisiableCtrlr();
            LblTitle.Visible = true;
            LblTitle.Text = @"Set Groups";
            LblPath.Visible = true;
            LblPath.Text = @"Groups separate by ""|"":";
            TxtGroups.Visible = true;
            BtnGroups.Visible = true;
            TxtGroups.Focus();
            TxtGroups.SelectAll();
        }

        private void BtnGroups_Click(object sender, EventArgs e)
        {
            //write groups info to ini file;
            string str;
            using (StreamReader sr = File.OpenText(VariableDefine.iniPath))
            {
                str = sr.ReadToEnd();
                str = str.Replace(@"[Groups]=" + VariableDefine.groups, @"[Groups]=" + TxtGroups.Text.Trim());
                sr.Close();
            }

            using (StreamWriter sw = new StreamWriter(VariableDefine.iniPath, false, Encoding.UTF8))
            {
                sw.Write(str);
                sw.Close();
            }
            VariableDefine.groups = TxtGroups.Text.Trim();
            initForm();
        }

        private void MiRate_Click(object sender, EventArgs e)
        {
            invisiableCtrlr();
            LblTitle.Visible = true;
            LblTitle.Text = @"Set Rates";
            LblPath.Visible = true;
            LblPath.Text = @"Rates separate by ""|"":";
            TxtRate.Visible = true;
            BtnRate.Visible = true;
            TxtRate.Focus();
            TxtRate.SelectAll();
        }

        private void BtnRate_Click(object sender, EventArgs e)
        {
            //write rates info to ini file;
            string str;
            using (StreamReader sr = File.OpenText(VariableDefine.iniPath))
            {
                str = sr.ReadToEnd();
                str = str.Replace(@"[Rates]=" + VariableDefine.rates, @"[Rates]=" + TxtRate.Text.Trim());
                sr.Close();
            }

            using (StreamWriter sw = new StreamWriter(VariableDefine.iniPath, false, Encoding.UTF8))
            {
                sw.Write(str);
                sw.Close();
            }
            VariableDefine.rates  = TxtRate.Text.Trim();
            initForm();
        }

        private void BtnPrevious_Click(object sender, EventArgs e)
        {
            if (TxtNowFile.Text == "1")
            {
                return;
            }
            else
            {
                PBShow.Image = imgMe(VariableDefine.alPicFileName[int.Parse(TxtNowFile.Text.Trim()) - 2].ToString());
                VariableDefine.strShowingPicFullName = VariableDefine.alPicFileName[int.Parse(TxtNowFile.Text.Trim()) - 2].ToString();
                getVote(VariableDefine.alPicFileName[int.Parse(TxtNowFile.Text.Trim()) - 2].ToString());
                int nowLoc = int.Parse(TxtNowFile.Text.Trim()) - 1;
                TxtNowFile.Text = nowLoc.ToString();
                TxtNowFile.SelectAll();
                TxtNowFile.Focus();
                
            }

        }

        private void getVote(string strPicName)
        {
            //select * from table where username,picture name;
            string[] strTmp=strPicName.Split('\\');
            string strShortName=strTmp[strTmp.Length-1];
            VariableDefine.meConn.Open();
            VariableDefine.meCmd.CommandText = @"SELECT GroupValue,RateValue,VoteBy,VoteTime FROM voteInfo WHERE PicMD5 ='"
                +VariableDefine.getFileMD5(strPicName)+"' ORDER BY VoteTime DESC";
            SqlCeResultSet meRs = VariableDefine.meCmd.ExecuteResultSet(ResultSetOptions.None);
            if (!meRs.Read())
            {
                //no record
                LBFileName.Text = strShortName + "\n\r(Nobody Vote It.)";
            }
            else
            {
                //got record
                string strGroupValue = meRs.GetString(0);
                string strRateValue = meRs.GetString(1);
                string strVoteBy = meRs.GetString(2);
                string strVoteTime = meRs.GetDateTime(3).ToString(VariableDefine.dateFormate);
                LBFileName.Text = strShortName + @"(" + strGroupValue + @"," 
                    + strRateValue + ")\n\r(last vote by " + strVoteBy + @" at " + strVoteTime + @")";
            }
            meRs.Close();
            VariableDefine.meConn.Close();
            
            //throw new Exception("The method or operation is not implemented.");
        }


        private void TxtNowFile_LostFocus(object sender, EventArgs e)
        {
            string strPrevious = TxtNowFile.Text.Trim();
            try
            {
                int.Parse(TxtNowFile.Text.Trim());
                if (int.Parse(TxtNowFile.Text.Trim()) == 0)
                {
                    TxtNowFile.Text = strPrevious;
                    TxtNowFile.SelectAll();
                    TxtNowFile.Focus();
                }
                if(int.Parse(TxtNowFile.Text.Trim())>VariableDefine.alPicFileName.Count)
                {
                    TxtNowFile.Text = strPrevious;
                    TxtNowFile.SelectAll();
                    TxtNowFile.Focus();
                }

            }
            catch
            {
                TxtNowFile.Text = strPrevious;
                TxtNowFile.SelectAll();
                TxtNowFile.Focus();
            }


        }

        private void BtnNext_Click(object sender, EventArgs e)
        {
            if (TxtNowFile.Text == VariableDefine.alPicFileName.Count.ToString())
            {
                return;
            }
            else
            {
                PBShow.Image = imgMe(VariableDefine.alPicFileName[int.Parse(TxtNowFile.Text.Trim())].ToString());
                VariableDefine.strShowingPicFullName = VariableDefine.alPicFileName[int.Parse(TxtNowFile.Text.Trim())].ToString();
                getVote(VariableDefine.alPicFileName[int.Parse(TxtNowFile.Text.Trim())].ToString());
                int nowLoc = int.Parse(TxtNowFile.Text.Trim()) + 1;
                TxtNowFile.Text = nowLoc.ToString();
                TxtNowFile.SelectAll();
                TxtNowFile.Focus();
            }
        }

        private void BtnTo_Click(object sender, EventArgs e)
        {
            PBShow.Image = imgMe(VariableDefine.alPicFileName[int.Parse(TxtNowFile.Text.Trim())-1].ToString());
            VariableDefine.strShowingPicFullName = VariableDefine.alPicFileName[int.Parse(TxtNowFile.Text.Trim())-1].ToString();
            getVote(VariableDefine.alPicFileName[int.Parse(TxtNowFile.Text.Trim()) - 1].ToString());
            int nowLoc = int.Parse(TxtNowFile.Text.Trim());
            TxtNowFile.Text = nowLoc.ToString();
            TxtNowFile.SelectAll();
            TxtNowFile.Focus();
        }

        private void BtnVote_Click(object sender, EventArgs e)
        {
            if ((CmbGroups.SelectedItem == null) || (CmbRate.SelectedItem == null))
            {
                MessageBox.Show("Forget someting?\n\rGroup or Rate?");
                return;
            }
            //insert vote;
            string strFullName, strGroup, strRate, strMD5,strVoteTime;
            strFullName = VariableDefine.strShowingPicFullName;
            strGroup = this.CmbGroups.SelectedItem.ToString();
            strRate = this.CmbRate.SelectedItem.ToString();
            strMD5 = VariableDefine.getFileMD5(strFullName);
            strVoteTime = DateTime.Now.ToString(VariableDefine.dateFormate);
            string[] strTmp = strFullName.Split('\\');
            string strShortName = strTmp[strTmp.Length - 1];
            VariableDefine.meConn.Open();
            VariableDefine.meCmd.CommandText = @"SELECT ID FROM voteInfo WHERE VoteBy='" + VariableDefine.user + @"' AND PicMD5='"
                + strMD5 + @"' ORDER BY VoteTime DESC";
            SqlCeResultSet meRs = VariableDefine.meCmd.ExecuteResultSet(ResultSetOptions.None);
            string strSQL;
            if (!meRs.Read())
            {
                //insert vote
                strSQL =
                    @"INSERT INTO voteInfo (PicFullName,GroupValue,RateValue,VoteBy,PicMD5,VoteTime,PicName) VALUES ('"
                    + strFullName + @"','" + strGroup + @"','" + strRate + @"','" + VariableDefine.user + @"','"
                    + strMD5 + @"','" + strVoteTime + @"','" +strShortName+@"')";
            }
            else
            {
                //update vote
                int rowID = meRs.GetInt32(0);
                strSQL =
                    "UPDATE voteInfo SET PicFullName='" + strFullName + "',GroupValue='" + strGroup
                    + "',RateValue='" + strRate + "',VoteTime='" + strVoteTime + "',PicName='" + strShortName 
                    + "' WHERE ID=" + rowID.ToString();

            }
            meRs.Close();
            VariableDefine.meCmd.CommandText = strSQL;
            VariableDefine.meCmd.ExecuteNonQuery();
            VariableDefine.meConn.Close();

            
            LBFileName.Text = strShortName + @"(" + strGroup + @","
                + strRate + ")\n\r(last vote by " + VariableDefine.user + @" at " + strVoteTime + @")";
        }

        private void MiSetting_Click(object sender, EventArgs e)
        {

        }

        private void initCmbUser()
        {
            VariableDefine.meConn.Open();
            VariableDefine.meCmd.CommandText = "SELECT UserName FROM userInfo WHERE Status=1 ORDER BY ID";
            SqlCeResultSet meRs = VariableDefine.meCmd.ExecuteResultSet(VariableDefine.meRSOptions);
            CmbUsers.Items.Clear();
            while (meRs.Read())
            {
                string s = meRs.GetString(0);
                if(s!=VariableDefine.user)
                    CmbUsers.Items.Add(s);
            }
            meRs.Close();
            VariableDefine.meConn.Close();
            //throw new Exception("The method or operation is not implemented.");
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (CmbUsers.SelectedItem == null)
            {
                return;
            }
            else
            {
                //Delete user
                VariableDefine.meConn.Open();
                string strSQLDelUser = @"DELETE FROM userInfo WHERE UserName='" + CmbUsers.SelectedItem.ToString() + "'";
                VariableDefine.meCmd.CommandText = strSQLDelUser;
                VariableDefine.meCmd.ExecuteNonQuery();

                //Delete votes
                if (ChkWhole.Checked)
                {
                    string strSQLDelVote = "DELETE FROM voteInfo WHERE VoteBy='" + CmbUsers.SelectedItem.ToString() + "'";
                    VariableDefine.meCmd.CommandText = strSQLDelVote;
                    int c=VariableDefine.meCmd.ExecuteNonQuery();
                }
                VariableDefine.meConn.Close();
                initCmbUser();
            }
        }

        private void MiUsers_Click(object sender, EventArgs e)
        {
            invisiableCtrlr();
            LblTitle.Visible = true;
            LblTitle.Text = @"Delete User";
            LblPath.Visible = true;
            LblPath.Text = @"Select user:";
            CmbUsers.Visible = true;
            initCmbUser();
            BtnDelete.Visible = true;
            ChkWhole.Visible = true;
            ChkWhole.Checked = false;
        }

        private void MiStat_Click(object sender, EventArgs e)
        {
            FrmStat frmStat = new FrmStat();
            frmStat.Show();
            this.Close();
        }


        [DllImport("ImageLoader.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr LoadBitmapFromFilename(IntPtr hdc, string szFileName);
        //public static extern IntPtr LoadBitmapFromResource(IntPtr hdc, uint dwResourceID, string pcszClass, IntPtr hModule);
        
        IntPtr m_hBitmap;
        IntPtr m_hWnd;
        IntPtr m_hDLL;

        private IntPtr LoadViaDLL(string flname)
        {
            
            //MessageBox.Show("Pause!");
            string filename = Path.Combine(VariableDefine.appPath, "MSDNres.DLL");
            this.Focus();
            this.Capture = true;
            m_hWnd = Win32.GetFocus();
            this.Capture = false;
            m_hDLL = Win32.LoadLibrary(filename);
            int t = Environment.TickCount;
            if (m_hDLL != IntPtr.Zero)
            {
                IntPtr hdc = Win32.GetDC(m_hWnd);
                //LoadBitmapFromFilename(hdc, flname);
                m_hBitmap = LoadBitmapFromFilename(hdc,flname);

                Win32.ReleaseDC(m_hWnd, hdc);
            }
            return m_hBitmap;
        }
    }
}